window.onload = function(){ //页面加载完毕触发

    //轮播图 开始
    var imgListUl = document.querySelector(".img-list"); //获取轮播图ul
    var imgAll = document.querySelectorAll(".banner .img-list img"); //获取轮播图所有图片img
    var pointerList = document.querySelectorAll(".pointer a"); //获取轮播图导航点
    
    var swiperButtonPrev = document.querySelector(".swiper-button-prev"); //获取轮播图上一个
    var swiperButtonNext = document.querySelector(".swiper-button-next"); //获取轮播图下一个

    swiperButtonPrev.onclick = function(){
        imgListUl.imgIndex--;
        lunboluRoll(500, 0);
    }
    swiperButtonNext.onclick = function(){
        imgListUl.imgIndex++;
        lunboluRoll(500, 1);
    }

    for(var i = 0; i < pointerList.length; i++) {
        let pointer_a = pointerList[i];
        pointer_a.index = i;
        pointer_a.onclick = function() { //点击圆点切换轮播
            imgListUl.imgIndex = this.index;
            lunboluRoll(500);
        }
    }
    
    function lunboluRoll(putOffMs){ //轮播图翻滚
        if(isNaN(putOffMs)) putOffMs = 0;
     
        if(imgListUl.imgIndex > imgListUl.childElementCount-1) {
            imgListUl.imgIndex = imgListUl.childElementCount-1;return;
        }else if(imgListUl.imgIndex < 0) {
            imgListUl.imgIndex = 0;return;
        }
        let pointerIndex = imgListUl.imgIndex;
        if(imgAll.length >= 2) {
            if(imgListUl.imgIndex == 0) pointerIndex = (pointerList.length-1);
            else if(pointerIndex > pointerList.length) pointerIndex = 0;
            else pointerIndex = (imgListUl.imgIndex-1);
        } 
        for(var i = 0; i < pointerList.length; i++) pointerList[i].classList.remove("active");
        pointerList[pointerIndex].classList.add("active");
        
        let imgObj = imgAll[imgListUl.imgIndex];
        let left = imgObj? -(imgObj.width * imgListUl.imgIndex): 0;
        imgListUl.style.transition = "all " + putOffMs + "ms";
        imgListUl.style.left = left+"px";
    }
    
    if(imgListUl.childElementCount >= 2) { //超过2张轮播图则补加前后图、复制最后放的放最前、复制最前放最后
        imgListUl.imgIndex = 1; //初次默认第一张图
        let firstLi = imgListUl.firstElementChild;
        let lastLi = imgListUl.lastElementChild;
        imgListUl.appendChild(firstLi.cloneNode(true));
        imgListUl.insertBefore(lastLi.cloneNode(true), firstLi);
        imgAll = document.querySelectorAll(".banner .img-list img");
    }else imgListUl.imgIndex = 0;

    imgListUl.addEventListener("transitionend", function(event) { //过度动画结束后触发事件
        //alert("过度属性名称:" + event.propertyName + ", 过渡已运行的秒数: " + event.elapsedTime);
        if(imgListUl.imgIndex == (imgAll.length-1)) {
            imgListUl.imgIndex = 1;
            lunboluRoll(0);
        }else if(imgListUl.imgIndex == 0) {
            imgListUl.imgIndex = imgAll.length-2;
            lunboluRoll(0);
        }
    });

    lunboluRoll(0); //首次加载轮播图
    //轮播图 结束
}
